import {
	defineStore
} from 'pinia';

//维护用户个人信息
export const useUserStore = defineStore('user', {
	state: () => ({
		userInfo: {
			name: "",
			avatarUrl: "",
			mail: ""
		},
		isGetUserInfo: false,
	}),

	actions: {
		setUserInfo(userInfo) {
			this.userInfo = userInfo;
			this.isGetUserInfo = true;
		},

		resetUserInfo() {
			this.userInfo = {
				name: "",
				avatarUrl: "",
				mail: ""
			};
			this.isGetUserInfo = false;
		},

		async fetchUserInfo(api, rhc) {
			try {
				// console.log('Fetching user info from:', `${api}/user/${userId}`);
				const response = await uni.request({
					url: `${api}/user/info`,
					header: {
						'Cookie': rhc
					}
				});

				const result = response.data.data;

				if (result) {
					console.log('User info fetched successfully:', result);
					this.setUserInfo(result);
				} else {
					console.log('No user info found.');
					this.resetUserInfo();
				}
			} catch (error) {
				console.error("Failed to fetch user info:", error);
				this.resetUserInfo();
			}
		}

	},

	getters: {
		hasUserInfo: (state) => !!state.userInfo.name && !!state.userInfo.avatarUrl && !!state.userInfo.mail,
	}
});